package com.xdjd.mobile.system.interceptor;

import com.alibaba.fastjson.JSON;
import com.gitee.easyopen.ApiContext;
import com.gitee.easyopen.ApiMeta;
import com.gitee.easyopen.ApiResult;
import com.gitee.easyopen.interceptor.ApiInterceptorAdapter;
import com.xdjd.mobile.business.entity.vo.LoginUser;
import com.xdjd.mobile.business.util.ResponseUtil;
import com.xdjd.mobile.system.ApiUtil;
import com.xdjd.mobile.system.anotations.ApiAuth;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogInterceptor extends ApiInterceptorAdapter {

	Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object serviceObj, Object argu)
            throws Exception {
        ApiResult result = new ApiResult();
        if (StringUtils.isBlank(ApiContext.getApiParam().fatchAccessToken())) {
            result.setCode(-101);
            result.setMsg("未登录");
            ResponseUtil.renderJson(response, JSON.toJSONString(result));
            return false;
        }
        LoginUser loginUser = ApiUtil.getCurrentUser();
        if (loginUser == null) {
            result.setCode(-101);
            result.setMsg("未登录");
            ResponseUtil.renderJson(response, JSON.toJSONString(result));
            return false;
        }
    	
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object serviceObj, Object argu,
                           Object result) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object serviceObj, Object argu, Object result, Exception e) throws Exception {
    }

    @Override
    public boolean match(ApiMeta apiMeta) {
        String name = apiMeta.getName();
        ApiAuth apiAuth = apiMeta.getMethod().getAnnotation(ApiAuth.class);
        if (name.startsWith("nologin") || apiAuth != null) {
            return false;
        }
        return true;
    }


}
